import 'dart:convert';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; //手机适配的兼容包
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:myjd/api/Home.dart';
import 'package:myjd/api/index.dart';
import 'package:myjd/config/MyColors.dart';
import 'package:myjd/utils/ScreenAdaper.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  /**
   * 初始化banners
   */
  List imgList = []; //轮播
  List topList = []; //喜欢
  List hotList = []; //热门
  String base64Img =
      "";

  @override
  void initState() {
    super.initState();
    this._getBanners();
    this._getHots();
  }

  /**
   * 获取熊猫优选的banners
   */
  _getBanners() async {
    var apiUrl = "http://www.xiongmaoyouxuan.com/api/tab/1?start=0";
    Response result = await HomeApi.getBannersAndLikes();
//    print(result.data["data"]["topList"]);
//    print(result.data is String);
//    print(result.data is Map);
//    print(result.data is List);
//    print((result.data));
//    print(json.encode(result.data) is String);
    setState(() {
      this.imgList = result.data["data"]["banners"];
      this.topList = result.data["data"]["topList"];
    });
  }

  _getHots() async {
    Response result = await HomeApi.getHots();
    print(result.data);
    this.hotList = result.data["result"];
  }

  /**
   * 轮播图模块
   */
  Widget _swiperWidget() {
    return Container(
      child: AspectRatio(
          aspectRatio: 1008 / 378,
          child: this.imgList.length != 0
              ? Swiper(
                  itemBuilder: (BuildContext context, int index) {
                    return new Image.network(
                      this.imgList[index]["imageUrl"],
                      fit: BoxFit.fill,
                    );
                  },
                  itemCount: this.imgList.length,
                  pagination: new SwiperPagination(
                      margin: new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 10.0),
                      builder: new DotSwiperPaginationBuilder(
                          color: Colors.white30,
                          activeColor: MyColors.theme,
                          size: 10.0,
                          activeSize: 12.0)),
                  autoplay: true)
              : Container(
                  color: Colors.black12,
                  child: Center(
                    child: Text('loading...'),
                  ),
                )),
    );
  }

  /**
   * 标题模块
   */
  Widget _titleWidget({String title, double fontSize = 26}) {
    return Container(
      height: ScreenAdaper.height(32),
      margin: EdgeInsets.only(left: ScreenAdaper.width(20)),
      padding: EdgeInsets.only(left: ScreenAdaper.width(20)),
      decoration: BoxDecoration(
          border: Border(
              left: BorderSide(
        color: Colors.red,
        width: ScreenAdaper.width(10),
      ))),
      child: Text(
        title,
        style: TextStyle(
          color: Colors.black54,
          fontWeight: FontWeight.bold,
          fontSize: ScreenAdaper.fontSize(fontSize),
        ),
      ),
    );
  }

  /**
   * 热门商品
   */
  Widget _hotProductListWidget() {
    var str = this.base64Img.split(',')[1];
    Uint8List bytes = Base64Decoder().convert(str);
//    print(bytes);
    return Container(
        height: ScreenAdaper.height(274), //20*2+140+44+10
        padding: EdgeInsets.all(ScreenAdaper.width(20)),
        child: Row(
          children: <Widget>[
            Container(
              height: double.infinity,
              width: ScreenAdaper.width(100),
              color: Colors.yellow,
              margin: EdgeInsets.only(
                  right: ScreenAdaper.width(20),
                  bottom: ScreenAdaper.width(20)),
              child: Center(
                child: Container(
                  width: ScreenAdaper.width(48),
                  height: ScreenAdaper.height(100),
                  child: bytes != null
                      ? Image.memory(bytes, fit: BoxFit.cover)
                      : Text(""),
                ),
              ),
            ),
            Expanded(
              flex: 1,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemBuilder: (contxt, index) {
                  return Column(
                    children: <Widget>[
                      Container(
                        height: ScreenAdaper.height(180),
                        width: ScreenAdaper.width(180),
                        margin: EdgeInsets.only(right: ScreenAdaper.width(21)),
                        child: Image.network(
//                    "https://www.itying.com/images/flutter/hot${index + 1}.jpg",
                            this.topList[index]["image"],
                            fit: BoxFit.cover),
                      ),
                      Container(
//                color: Colors.red,
                        width: ScreenAdaper.width(180),
                        padding: EdgeInsets.only(top: ScreenAdaper.height(10)),
                        height: ScreenAdaper.height(44),
                        child: Text(
                          this.topList[index]["title"],
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                        ),
                      )
                    ],
                  );
                },
                itemCount: this.topList.length,
              ),
            )
          ],
        ));
  }

  /**
   * 推荐商品
   */
  Widget _recProductItemWidget(Map ele) {
    var itemWidth = (ScreenAdaper.getScreenWidth() - 30) / 2;
    return Container(
      width: itemWidth,
      padding: EdgeInsets.all(5),
      decoration: BoxDecoration(
          border:
              Border.all(color: Color.fromRGBO(233, 233, 233, 0.9), width: 1)),
      child: Column(
        children: <Widget>[
          Container(
              width: double.infinity,
              child: AspectRatio(
                aspectRatio: 1 / 1,
                child: Image.network(
                    ApiBase.baseURL + ele["s_pic"].replaceAll("\\", "/"),
                    fit: BoxFit.cover),
              )),
          Padding(
            padding: EdgeInsets.only(top: ScreenAdaper.height(20)),
            child: Text(
              ele["title"],
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: Colors.black54),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: ScreenAdaper.height(20)),
            child: Stack(
              children: <Widget>[
                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    ele["price"].toString(),
                    style: TextStyle(color: Colors.red, fontSize: 16),
                  ),
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child: Text(ele["old_price"].toString(),
                      style: TextStyle(
                          color: Colors.black54,
                          fontSize: 14,
                          decoration: TextDecoration.lineThrough)),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    //传入设计稿的宽度，以后直接写设计稿的宽度即可.
    ScreenAdaper.init(context);
    return ListView(
      children: <Widget>[
        this._swiperWidget(),
        SizedBox(
          height: ScreenAdaper.height(20),
        ),
        this._titleWidget(title: "猜你喜欢"),
        SizedBox(
          height: ScreenAdaper.height(20),
        ),
        this._hotProductListWidget(),
        this._titleWidget(title: "热门推荐"),
        Container(
            padding: EdgeInsets.all(10),
//            color: Colors.red,
            child: Wrap(
                runSpacing: 10,
                spacing: 10,
                children: this.hotList.map((ele) {
                  return _recProductItemWidget(ele);
                }).toList()))
      ],
    );
  }
}
